<template>
  <view class="address-edit">
    <view class="header">
      <text class="title">{{isEdit? '编辑地址' : '新增地址'}}</text>
    </view>

    <view class="form-container">
      <view class="form-item">
        <text class="label">收货人</text>
        <input 
          type="text"
          v-model="formData.name"
          placeholder="请输入收货人姓名"
          class="input"
        />
      </view>

      <view class="form-item">
        <text class="label">手机号码</text>
        <input 
          type="text" 
          v-model="formData.phone"
          placeholder="请输入手机号码"
          maxlength="11"
          class="input"
        />
      </view>

      <view class="form-item">
        <text class="label">所在城市</text>
        <view class="city-input-group">
          <input 
            type="text"
            v-model="formData.city"
            placeholder="请输入或选择所在城市"
            class="input"
          />
          <picker mode="selector" :range="cityList" @change="onCityChange" :value="cityIndex">
            <view class="picker-icon">▼</view>
          </picker>
        </view>
      </view>

      <view class="form-item">
        <text class="label">小区/大厦</text>
        <input 
          type="text"
          v-model="formData.department"
          placeholder="请输入小区/大厦名称"
          class="input"
        />
      </view>

      <view class="form-item">
        <text class="label">楼号/门牌</text>
        <input 
          type="text"
          v-model="formData.houseNumber"
          placeholder="请输入详细楼号/门牌号"
          class="input"
        />
      </view>

      <view class="form-item switch-item">
        <text class="label">设为默认地址</text>
        <switch 
          :checked="formData.isDefault"
          @change="handleDefaultChange"
          color="#1b76f6"
        />
      </view>
    </view>

    <view class="footer">
      <button class="save-btn" @click="handleSave">保存</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isEdit: false,
      userId: '',
      formData: {
        id: '',
        name: '',
        phone: '',
        city: '',
        department: '',
        houseNumber: '',
        isDefault: false
      },
      cityList: [
        '北京', '上海', '洛阳', '天津', '成都', '杭州', '武汉', '西安',
        '南京', '重庆',  '苏州', '长沙', '郑州', '徐州', '青岛',
        '宁波', '昆明', '大连', '厦门', '合肥', '佛山', '福州', '哈尔滨',
        '济南', '南昌', '长春', '太原', '贵阳', '石家庄', '泉州','新疆','西藏',
        '南宁', '海口', '呼和浩特', '乌鲁木齐', '兰州', '西宁', '银川', '拉萨'
      ],
      cityIndex: 0
    }
  },

  onLoad(options) {
    const userInfo = uni.getStorageSync('userInfo')
    if (userInfo) {
      this.userId = JSON.parse(userInfo)._id
    }

    if (options.address) {
      this.isEdit = true
      const address = JSON.parse(decodeURIComponent(options.address))
      this.formData = { ...address }
      this.cityIndex = this.cityList.indexOf(this.formData.city) >= 0 ? this.cityList.indexOf(this.formData.city) : 0;
    }
  },

  methods: {
    handleDefaultChange(e) {
      this.formData.isDefault = e.detail.value
    },

    validateForm() {
      if (!this.formData.name) {
        uni.showToast({
          title: '请输入收货人姓名',
          icon: 'none'
        })
        return false
      }

      if (!this.formData.phone) {
        uni.showToast({
          title: '请输入手机号码',
          icon: 'none'
        })
        return false
      }

      if (!/^1[3-9]\d{9}$/.test(this.formData.phone)) {
        uni.showToast({
          title: '手机号码格式不正确',
          icon: 'none'
        })
        return false
      }

      if (!this.formData.city) {
        uni.showToast({
          title: '请输入或选择所在城市',
          icon: 'none'
        })
        return false
      }

      if (!this.formData.department) {
        uni.showToast({
          title: '请输入小区/大厦名称',
          icon: 'none'
        })
        return false
      }

      if (!this.formData.houseNumber) {
        uni.showToast({
          title: '请输入楼号/门牌号',
          icon: 'none'
        })
        return false
      }

      return true
    },

    onCityChange(e) {
      this.cityIndex = e.detail.value;
      this.formData.city = this.cityList[this.cityIndex];
    },

    async handleSave() {
      if (!this.validateForm()) return

      try {
        const getUserResponse = await uni.request({
          url: 'https://67f85eae7719dfcd4b47e8f1.hz-iframe-svc.simplelab.cn/users',
          method: 'GET'
        })

        if (getUserResponse.statusCode !== 200) {
          throw new Error('获取用户数据失败')
        }

        const users = getUserResponse.data
        const currentUser = users.find(user => user.id === this.userId)

        if (!currentUser) {
          throw new Error('用户不存在')
        }

        let addresses = currentUser.addresses || []
        const now = new Date().toISOString()

        if (!this.isEdit && addresses.length === 0) {
          this.formData.isDefault = true
        }

        if (this.formData.isDefault) {
          addresses = addresses.map(addr => ({
            ...addr,
            isDefault: false
          }))
        }

        if (this.isEdit) {
          addresses = addresses.map(addr => 
            addr.id === this.formData.id 
              ? { ...this.formData, updatedAt: now }
              : addr
          )
        } else {
          const newAddress = {
            ...this.formData,
            id: Date.now().toString(),
            createdAt: now,
            updatedAt: now
          }
          addresses.push(newAddress)
        }

        const updateResponse = await uni.request({
          url: `https://67f85eae7719dfcd4b47e8f1.hz-iframe-svc.simplelab.cn/users/${this.userId}`,
          method: 'PUT',
          data: {
            ...currentUser,
            addresses
          }
        })

        if (updateResponse.statusCode === 200) {
          uni.showToast({
            title: this.isEdit ? '修改成功' : '保存成功',
            icon: 'success'
          })

          setTimeout(() => {
            const pages = getCurrentPages()
            const prevPage = pages[pages.length - 2]
            if (prevPage && prevPage.$vm.fetchAddresses) {
              prevPage.$vm.fetchAddresses()
            }
            uni.navigateBack()
          }, 1500)
        } else {
          throw new Error('保存失败')
        }
      } catch (error) {
        uni.showToast({
          title: error.message || '保存失败，请重试',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style scoped>
.address-edit {
  min-height: 100vh;
  background-color: #f7f7f7;
  display: flex;
  flex-direction: column;
}

.header {
  height: 88rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  position: relative;
  border-bottom: 1rpx solid #f0f0f0;
}

.header .back-btn {
  padding: 10rpx;
}

.header .title {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  font-size: 34rpx;
  font-weight: 500;
  color: #333;
}

.form-container {
  flex: 1;
  padding: 30rpx;
  background-color: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.form-item {
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.form-item:last-child {
  border-bottom: none;
}

.form-item .label {
  display: block;
  font-size: 30rpx;
  color: #333;
  margin-bottom: 20rpx;
  font-weight: 500;
}

.form-item .input {
  width: 100%;
  height: 80rpx;
  font-size: 30rpx;
  color: #333;
  padding: 0;
}

.form-item .placeholder {
  color: #999;
  font-size: 28rpx;
}

.form-item .picker {
  width: 100%;
  height: 80rpx;
  display: flex;
  align-items: center;
}

.form-item .picker .picker-view {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-item .picker .picker-text {
  font-size: 30rpx;
  color: #333;
}

.form-item .picker .picker-text.placeholder {
  color: #999;
}

.switch-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.city-input-group {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.city-input-group .input {
  flex: 1;
  margin-right: 20rpx;
}

.city-input-group .picker-icon {
  font-size: 30rpx;
}

.footer {
  margin-bottom: 40px;
  padding: 30rpx;
  background-color: #fff;
  border-top: 1rpx solid #f0f0f0;
}

.footer .save-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  background-color: #1b76f6;
  color: #fff;
  font-size: 32rpx;
  border-radius: 44rpx;
  border: none;
}

.footer .save-btn:active {
  opacity: 0.9;
}

.footer .save-btn.disabled {
  background-color: #ccc;
  opacity: 0.7;
}
</style>    